import router, { asyncRoutes } from '@/router'
import store from '@/store'
// 虚拟进度条 NProgress.start()开始进度条 .done()进度条结束
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import getPageTitle from './utils/get-page-title'
// import { asyncRoutes } from '@/router'
// 路由守卫, 2个函数 --- 狗子函数,在进入页面开始的时候自动执行
// 白名单:项目里面 不需要登录就可以看得到的页面 注册面 登录页面 404 等
// const whiteList = ['/login', '/404']
const whiteList = ['/login']

// 进入页面之前执行的钩子函数
router.beforeEach(async(to, from, next) => {
//   console.log(to, from, next)
// 获取vuex中的token
  // document.title = getPageTitle(to.meta.title)
  console.log(document)
  document.title = getPageTitle(to.meta.title)
  NProgress.start()
  const token = store.state.user.token
  if (token) {
    if (whiteList.includes(to.path)) {
      next('/')
      NProgress.done()
    } else {
      if (!store.state.user.userInfo.id) {
        // console.log(123)
        const res = await store.dispatch('user/getUserInfoActions')
        console.log('用户详细信息接口的返回值', res)
        router.addRoutes(asyncRoutes)
        const filterRouters = asyncRoutes.filter(item => {
          const currentName = item.children[0].name
          return res.includes(currentName)
        })
        filterRouters.push({ path: '*', redirect: '/404', hidden: true })
        console.log('过滤后路由', filterRouters)
        router.addRoutes(filterRouters)
        // store.commit('menu/setMenuList', asyncRoutes)
        store.commit('menu/setMenuList', filterRouters)

        // 添加的页面
        next({
          ...to,
          replace: true
        })
      }
      next()
      // await store.dispatch('user/getUserInfoActions')
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})
// 进入页面之后执行的钩子函数
// afterEach 并不一定都会执行, 如果在进去的beforeEach钩子函数里面
// next('参数')跳转到了其他页面(将正常的跳转方向给他改变了),这个afterEach就不会执行
router.afterEach(() => {
  NProgress.done()
})
